#include "header.h"

extern char CompressionServerIP[MAX_IPV4_IP_LEN];

int getCompressionServer(void)
{
	int ret = SUCCESS, sock;
	unsigned int socklen;
	char buffer[MAX_PKT_SIZE], *identifier_1, *identifier_2;
	struct sockaddr_in saddr;
	struct in_addr iaddr;

	memset(&saddr, 0, sizeof(struct sockaddr_in));
	memset(&iaddr, 0, sizeof(struct in_addr));

	sock = socket(PF_INET, SOCK_DGRAM, 0);
	if ( sock < 0 ) {
		perror("Error creating socket");
		ret = FAILURE;
		goto end;
	}

	saddr.sin_family = PF_INET;
	saddr.sin_port = htons(0);
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);

	ret = bind(sock, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in));
	if ( ret < 0 ) {
    	perror("Error binding socket to interface");
		ret = FAILURE;
		close(sock);
		goto end;
	}

	iaddr.s_addr = INADDR_ANY;

	//Set the outgoing interface to DEFAULT
	setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &iaddr, sizeof(struct in_addr));

	//set destination multicast address
	saddr.sin_family = PF_INET;
	saddr.sin_addr.s_addr = inet_addr(MULTICAST_IP);
	saddr.sin_port = htons(MULTICAST_PORT);

	//Copy multicast message to buffer
	strcpy(buffer, MULTICAST_COMPRESSION_REQ_MSG);

	socklen = sizeof(struct sockaddr_in);
	ret = sendto(sock, buffer, 100, 0, (struct sockaddr *)&saddr, socklen);
	ret = sendto(sock, buffer, 100, 0, (struct sockaddr *)&saddr, socklen);
	ret = sendto(sock, buffer, 100, 0, (struct sockaddr *)&saddr, socklen);
	ret = sendto(sock, buffer, 100, 0, (struct sockaddr *)&saddr, socklen);
	ret = sendto(sock, buffer, 100, 0, (struct sockaddr *)&saddr, socklen);
	if (FAILURE == ret) {
		perror("Failed to send multicast message");
		ret = FAILURE;
		close(sock);
		goto end;
	}

	ret = recvfrom(sock, buffer, 100, 0, (struct sockaddr *)&saddr, &socklen);
	if (FAILURE == ret) {
		printf("Failed to recieve multicast message\n");
		ret = FAILURE;
		close(sock);
		goto end;
	}

	if (SUCCESS == strncmp(buffer, MULTICAST_COMPRESSION_RES_MSG, strlen(MULTICAST_COMPRESSION_RES_MSG))) {
		identifier_1 = strstr(buffer, "@");
		identifier_2 = strstr(buffer, "#");

		if (NULL == identifier_1 || NULL == identifier_2) {
			printf("Unable to resolve decompression server IP address\n");
			close(sock);
			goto end;
		}

		strncpy(CompressionServerIP, identifier_1+1, identifier_2-identifier_1-1);

		ret = SUCCESS;
	} else {
		ret = FAILURE;
	}

	close(sock);

end:
	return ret;
}

